<?php

// 设置数据库连接的初始值
header('content-type:text/html; charset=utf-8');
$servername = "localhost";
$username = "root";
$password = "020913";
$dbname = "part09"; // 数据库名称

// conn
// 获取数据库连接，命名为 mysqli 或者 conn
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
    die("连接失败: ".$conn->connect_error);
}
$conn->set_charset('utf8'); // 设置字符集

// 用户注册，插入新的数据到数据库
function register($conn)
{
    // mysqli_stmt
    // 插入数据库                       
    $sql = "INSERT INTO user(username, password, age, gender) VALUES(?, ?, ?, ?)";
    $mysqli_stmt = $conn->prepare($sql); // 准备预处理语句

    // 获取页面上提交的数据
    $username = $_POST["username"];
    $password = $_POST["password"];
    $age = $_POST["age"];
    $gender = $_POST["gender"];

    // s: string    i: int
    $mysqli_stmt->bind_param('ssii', $username, $password, $age, $gender);

    // 执行预处理的语句
    if($mysqli_stmt->execute()){
        // echo $mysqli_stmt->insert_id; // 程序执行成功，返回插入数据表的行 id
        echo PHP_EOL;
        echo "<script>alert('注册成功!!!'); window.location.href='../../views/office/login.html'</script>";
    }else{
        echo $mysqli_stmt->error; // 执行失败，展示错误信息
    }

    $mysqli_stmt->free_result();
    $mysqli_stmt->close();
}

// 用户注册，插入新的数据到数据库
register($conn);

// 释放结果集
$conn->close(); 
